using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ExamPaperEditingSystem.Models;

namespace ExamPaperEditingSystem.Services
{
    public class ChatService : IChatService
    {
        private readonly HttpClient _httpClient;
        private const string OnlineApiUrl = "http://50844s9656.wocp.fun:42440/v1/chat/completions";
        private const string LocalApiUrl = "http://192.168.100.71:8000/v1/chat/completions";

        public ChatService()
        {
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromMinutes(5);
        }

        public bool IsOnlineApiAvailable { get; private set; }
        public bool IsLocalApiAvailable { get; private set; }

        public async Task<ChatMessage> SendMessageAsync(string message, List<ChatMessage> history, string? apiUrl = null)
        {
            string targetUrl = apiUrl ?? await GetAvailableApiUrlAsync();
            
            var messages = new List<object>();
            
            // 添加历史消息
            foreach (var msg in history)
            {
                messages.Add(new
                {
                    role = msg.Role,
                    content = msg.Content
                });
            }
            
            // 添加当前消息
            messages.Add(new
            {
                role = "user",
                content = message
            });

            var requestBody = new
            {
                model = targetUrl.Contains("192.168.100.71") ? "deepseek-r1-70b" : "qwenlong-l1-32b",
                messages = messages,
                stream = false,
                temperature = 0.7,
                max_tokens = 4000
            };

            var json = JsonSerializer.Serialize(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                var response = await _httpClient.PostAsync(targetUrl, content);
                response.EnsureSuccessStatusCode();

                var responseJson = await response.Content.ReadAsStringAsync();
                var chatResponse = JsonSerializer.Deserialize<JsonElement>(responseJson);

                var assistantMessage = chatResponse
                    .GetProperty("choices")
                    .EnumerateArray()
                    .First()
                    .GetProperty("message")
                    .GetProperty("content")
                    .GetString() ?? string.Empty;

                var chatMessage = new ChatMessage
                {
                    Role = "assistant",
                    Content = RemoveThinkingContent(assistantMessage),
                    Timestamp = DateTime.Now
                };

                // 检查是否包含思维链内容
                var thinkingContent = ExtractThinkingContent(assistantMessage);
                if (!string.IsNullOrEmpty(thinkingContent))
                {
                    chatMessage.IsThinking = true;
                    chatMessage.ThinkingContent = thinkingContent;
                }

                return chatMessage;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"发送消息失败: {ex.Message}", ex);
            }
        }

        public async Task<string> StreamMessageAsync(string message, List<ChatMessage> history, string? apiUrl = null)
        {
            // 流式响应实现（简化版本）
            var result = await SendMessageAsync(message, history, apiUrl);
            return result.Content;
        }

        public async Task<bool> TestApiConnectionAsync(string apiUrl)
        {
            try
            {
                var testRequest = new
                {
                    model = apiUrl.Contains("192.168.100.71") ? "deepseek-r1-70b" : "qwenlong-l1-32b",
                    messages = new[]
                    {
                        new { role = "user", content = "你好" }
                    },
                    stream = false,
                    max_tokens = 10
                };

                var json = JsonSerializer.Serialize(testRequest);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync(apiUrl, content);
                
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }

        public string ExtractThinkingContent(string content)
        {
            // 提取思维链内容的正则表达式模式
            var patterns = new[]
            {
                @"<think>(.*?)</think>",
                @"<thinking>(.*?)</thinking>",
                @"思考过程：(.*?)(?=\n\n|$)",
                @"分析：(.*?)(?=\n\n|$)"
            };

            foreach (var pattern in patterns)
            {
                var match = Regex.Match(content, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    return match.Groups[1].Value.Trim();
                }
            }

            return string.Empty;
        }

        public string RemoveThinkingContent(string content)
        {
            // 移除思维链内容的正则表达式模式
            var patterns = new[]
            {
                @"<think>.*?</think>",
                @"<thinking>.*?</thinking>",
                @"思考过程：.*?(?=\n\n|$)",
                @"分析：.*?(?=\n\n|$)"
            };

            string result = content;
            foreach (var pattern in patterns)
            {
                result = Regex.Replace(result, pattern, "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
            }

            return result.Trim();
        }

        private async Task<string> GetAvailableApiUrlAsync()
        {
            // 首先测试本地API
            IsLocalApiAvailable = await TestApiConnectionAsync(LocalApiUrl);
            if (IsLocalApiAvailable)
            {
                return LocalApiUrl;
            }

            // 然后测试在线API
            IsOnlineApiAvailable = await TestApiConnectionAsync(OnlineApiUrl);
            if (IsOnlineApiAvailable)
            {
                return OnlineApiUrl;
            }

            throw new InvalidOperationException("没有可用的聊天API服务");
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}